import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class UtilsService {

    /**
    * [判断是否为空]
    * @Author   zhanggongze
    * @DateTime 2017-04-18
    * @search    {[any]}    str [任意类型]
    * return   {Boolean}       [返回布尔值]
    */
    isNull(str: string | null) {
        if (str != null && str != '' && typeof (str) != "undefined") {
            return false;
        } else {
            return true;
        }
    };
    //获取url 参数
    getQueryValue(queryName: string) {
        var query = decodeURIComponent(location.hash.split("?")[1]);
        var vars = query.split("&");

        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == queryName) { return pair[1]; }
        }
        return null;
    }
    random_string(len: number) {

        len = len || 32;

        let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        let maxPos = chars.length;
        let pwd = '';

        for (var i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    //科学计数法
    scientificNumber(n: { toString: () => any; }) {

        let number = n.toString();

        if (number.indexOf('.') === -1 && number.length > 7 && number.substr(number.length - 4, 4) === "0000") {

            let sN = '';
            let sZ = '';

            for (let i = 0; i < number.length; i++) {

                if (number.charAt(i) != 0) {
                    if (i == 1) {
                        sN += '.';
                    }
                    sN += number.charAt(i);
                } else {
                    sZ += number.charAt(i);
                }
            }

            let ws = sZ.length + (sN.length - 2);
            let snumber = sN + '*10^' + ws;
            // debugger

            return snumber;

        } else {
            return n;
        }
    }


    //计算年龄
    dobFormate(str: string | number | Date) {
        let date: any = new Date(str)
        let curDate: any = new Date()
        let date1 = Date.parse(date)
        let date2 = Date.parse(curDate)
        let day = Math.ceil((date2 - date1) / (60 * 60 * 1000 * 24))
        let age = ''
        let year = Math.floor(day / 365)
        let y = day % 365
        let month = Math.floor(y / 30)
        let d = Math.floor(day % 365 % 30)
        if (year > 0) {
            age += year + '岁'
        } else {
            if (month > 0) {
                age += month + '月'
            }
            if (d > 0) {
                age += d + '天'
            }
        }
        return age;
    }

    //判断是否是数组
    isArray(o: any) {
        return Object.prototype.toString.call(o) == '[object Array]';
    }

    //获取hash值
    getHashParameters() {

        var arr = (decodeURI(location.hash) || "").replace(/^\#/, '').split("&");

        if (arr.length > 1) {
            var params: any = {};
            for (var i = 0; i < arr.length; i++) {
                var data = arr[i].split("=");
                if (data.length == 2) {
                    params[data[0]] = data[1];
                }
            }
            return params;
        } else {

            return false;
        }

    }

    //链接添加hash
    hashSave(items?: { [x: string]: any; hasOwnProperty: (arg0: string) => any; }) {

        // let href = window.location.origin + window.location.pathname;
        // let hash = '#';
        // for (const key in items) {
        //     if (items.hasOwnProperty(key)) {
        //         const element = items[key];
        //         hash += ('&' + key + '=' + element);
        //     }
        // }

        // window.location.href = href + hash


        let href = window.location.origin + window.location.pathname;
        let hashRoute = window.location.hash.split('#')[1];
        let hash = '#';
        for (const key in items) {
            if (items.hasOwnProperty(key)) {
                const element = items[key];
                hash += ('&' + key + '=' + element);
            }
        }
        window.location.href = href + '#' + hashRoute + hash


    }

    /**
     * [nubChinese 将数字转中文字]
     * @Author   zhanggongze
     * @DateTime 2017-05-06
     * param    {[nub]}    nub [要转化的数字]
     */
    nubChinese(nub: any) {
        var chNub = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        return chNub[nub];
    }
    /**
    *时间格式化 
    * ps:<b>现在时间：{{nowDate | datez:"yyyy-MM-dd hh:mm"}}</b>
     */
    formate(value: any, fmt: any): any {

        value = new Date(value);

        let o: any = {
            "M+": value.getMonth() + 1, //月份 
            "d+": value.getDate(), //日 
            "h+": value.getHours(), //小时 
            "m+": value.getMinutes(), //分 
            "s+": value.getSeconds(), //秒 
            "q+": Math.floor((value.getMonth() + 3) / 3), //季度 
            "S": value.getMilliseconds() //毫秒 
        };

        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (value.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

        return fmt;
    }
    /**
     * 
     * @param array 数组
     * @param dx 删除指定下表
     */
    arrayRemove(array: any, dx: number): any {
        if (isNaN(dx) || dx > array.length) { return false; }
        for (var i = 0, n = 0; i < array.length; i++) {
            if (array[i] != array[dx]) {
                array[n++] = array[i]
            }
        }
        array.length -= 1
    }

    /**
     * json 合并
     * @param jsonbject1 
     * @param jsonbject2 
     */
    jsonExtend(jsonbject1: { [x: string]: any; }, jsonbject2: { [x: string]: any; }) {
        var resultJsonObject: any = {};
        for (var attr in jsonbject1) {
            resultJsonObject[attr] = jsonbject1[attr];
        }
        for (var attr in jsonbject2) {
            resultJsonObject[attr] = jsonbject2[attr];
        }
        return resultJsonObject;
    }


    /**
     * 根据数据对象的某个属性排序   this.agentItems.sort(this.utils.sortBycompare('Index'));
     * @param property 某个属性
     */
    sortBycompare(property: string | number) {
        return function (a: { [x: string]: any; }, b: { [x: string]: any; }) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }

    /**
  * 城市处理数据方法类
  * @param cityAll 
  */
    formateCity(cityAll: { [x: string]: any; }) {

        //省市区
        let province = [], city = [], area = [];
        //格式化后 省市区
        let fmCity = []

        for (const key in cityAll) {

            const element = cityAll[key];

            //省
            if (key == '86') {

                //省
                province.push(element);

                for (const key in element) {

                    const _element = element[key];

                    let o = {
                        value: key,
                        label: _element,
                        number: key
                    }
                    fmCity.push(o);
                }
            } else {

                //市
                fmCity.forEach((item: any) => {

                    if (key == item.number) {

                        let o;
                        item.children = [];

                        for (const _city in element) {

                            const _cityName = element[_city];

                            //市
                            city.push(element);

                            o = {
                                value: _city,
                                label: _cityName,
                                number: _city,
                                isLeaf: true
                            }

                            item.children.push(o)
                        }
                    }
                });

            }

        }

        return fmCity

    }

    // 省市区 初始化
    formateCityArea(cityAll: { [x: string]: any; }) {

        //省市区
        let province = [], city = [], area = [];
        //格式化后 省市区
        let fmCity = []

        for (const key in cityAll) {

            const element = cityAll[key];

            //省
            if (key == '86') {

                //省
                province.push(element);

                for (const key in element) {

                    const _element = element[key];

                    let o = {
                        value: key,
                        label: _element,
                        number: key
                    }
                    fmCity.push(o);
                }
            } else {
                //市
                fmCity.forEach((item: any) => {

                    if (key == item.number) {

                        let o;
                        item.children = [];

                        for (const _city in element) {

                            const _cityName = element[_city];

                            //市
                            city.push(element);

                            //区
                            const elementArea = cityAll[_city];

                            let _area = [];
                            if (elementArea) {
                                for (const _areaKey in elementArea) {
                                    let oA = {
                                        value: _areaKey,
                                        label: elementArea[_areaKey],
                                        number: _areaKey,
                                        isLeaf: true
                                    }
                                    _area.push(oA);
                                }
                            }


                            o = {
                                value: _city,
                                label: _cityName,
                                number: _city,
                                children: _area,
                                // isLeaf: true
                            }
                            if (_area.length === 0) {
                                Object.assign(o, { isLeaf: true });
                            }

                            item.children.push(o)
                        }
                    }

                });
            }
        }

        return fmCity
    }

    /**
 * 数组去重
 * @param array 
 */
    formatConcatArr(array: any) {
        let arr = array
        let i
        let j
        let len = arr.length
        for (i = 0; i < len; i++) {
            for (j = i + 1; j < len; j++) {
                if (arr[i] === arr[j]) {
                    arr.splice(j, 1)
                    len--
                    j--
                }
            }
        }
        return arr
    }

    formatGMTDate(str: string | number | Date) {
        if (!str) {
            return ''
        }
        let date = new Date(str)
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()

        const hour = date.getHours()
        const minute = date.getMinutes()
        // const second = date.getSeconds()

        const t1 = [year, month, day].map(this.formatNumber).join('-')
        const t2 = [hour, minute].map(this.formatNumber).join(':')

        return `${t1}T${t2}+08:00`
    }


    formatNumber(n: { toString: () => any; }) {
        const str = n.toString()
        return str[1] ? str : `0${str}`
    }

    stringToGuid(_str: any) {
        var str = _str;
        var lengths = [8, 4, 4, 4, 12];
        var parts = [];
        var range = 0;
        for (var i = 0; i < lengths.length; i++) {
            parts.push(str.slice(range, range + lengths[i]));
            range += lengths[i];
        };

        if (_str.indexOf("-") != -1) {
            return _str;
        } else {
            return parts.join('-');
        }
    }


    guid() {
        return ((this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4())).toUpperCase();
    }

    private S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

}